package com.maxmlr.framework.mybatisplus.statement;

import com.maxmlr.framework.mybatisplus.config.Configuration;
import com.maxmlr.framework.mybatisplus.mapper.MapperData;
import com.maxmlr.framework.mybatisplus.result.ResultSetHandler;
import lombok.AllArgsConstructor;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * @ClassName MappedStatement
 * @Description TODO
 * @Author maxiao
 * @Date 2020/3/23 上午11:26
 * @Version V1.0
 */
@AllArgsConstructor
public class StatementHandler {

    private final Configuration configuration;

    private final ResultSetHandler resultSetHandler;

    public <T> List<T> query(MapperData<T> mapperData, Object parameter) throws Exception {
        try {
            //JDBC
            Connection conn = getConnection();
            //TODO ParamenterHandler
            PreparedStatement pstmt = conn.prepareStatement(String.format(mapperData.getSql(), Integer.parseInt(String.valueOf(parameter))));
            pstmt.execute();
            //ResultSetHandler
            return resultSetHandler.handle(pstmt, mapperData);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }


    public Connection getConnection() throws SQLException {
        String driver = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://47.107.172.86:3306/cat?useUnicode=true&characterEncoding=utf8";
        String username = "maxiao";
        String password = "cniavj";
        Connection conn = null;
        try {
            Class.forName(driver); //classLoader,加载对应驱动
            conn = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
}
